#!/usr/bin/env python
# -*- coding:utf-8 -*-
import base64
import subprocess
import chardet
from config import config
import hashlib
import os
from urllib.parse import quote,unquote,quote_plus
from singleUi import searchUi
from samllToolApi.sqlEncode import spaceToComment,doublewrite

path = os.path.abspath(os.path.dirname(__file__))
hashtxt = path + os.sep + "dict" + os.sep
def base64_coder(coderStr):
    try:
        str_coder = base64.b64encode(coderStr.encode('utf-8'))
        return str_coder.decode('utf-8')
    except Exception as e:
        print(e)
        return "编码错误!"

def base64_encoder(encodeStr):
    try:
        str_encoder = base64.b64decode(encodeStr).decode("utf-8")
        return str_encoder
    except Exception as e:
        print(e)
        return "解码错误!"

def runCmd(cmd):
    res = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
    res.wait()
    return res#返回码、输出、错误、进程号

def killPid(res):
    res.kill()
    
def cmdExec(cmd:str,control):
    conf = config()
    if cmd.startswith("hydra"):
        hydra = conf.get_hydra_path()
        cmd = hydra + cmd
    r = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    while True:
        line = r.stdout.readline()
        if line == b'':
            break
        if type(line) == bytes:
            if chardet.detect(line)["encoding"] == "GB2312":
                line = line.strip().decode('gbk')
            else:
                line = bytes.decode(line,errors='ignore')
        control.AppendText(line + "\n")

def websphereXorDecoder(codeStr):
    try:
        password = ""
        for i in base64.b64decode(codeStr).decode("utf-8"):
            password += chr(ord(i) ^ ord('_'))
        return password
    except Exception as e:
        print(e)
        return None
def hashMd5(codeStr):
    try:
        result = hashlib.md5(codeStr.encode("UTF-8")).hexdigest()
        return result.upper()
    except Exception as e:
        print(e)
        return None
def hashSha1(codeStr):
    try:
        result = hashlib.sha1(codeStr.encode("UTF-8")).hexdigest()
        return result.upper()
    except Exception as e:
        print(e)
        return None

def hashSha256(codeStr):
    try:
        result = hashlib.sha256(codeStr.encode("UTF-8")).hexdigest()
        return result.upper()
    except Exception as e:
        print(e)
        return None
def hashSha512(codeStr):
    try:
        result = hashlib.sha512(codeStr.encode("UTF-8")).hexdigest()
        return result.upper()
    except Exception as e:
        print(e)
        return None
def hashCrackSimple(wordList,codeStr,hashType):
    try:
        found = ""
        filePath = hashtxt + wordList
        with open(filePath,mode="r") as readfile:
            for w in readfile.readlines():
                h = hashlib.new(hashType)
                h.update(w.strip().encode("utf-8"))
                if h.hexdigest().upper() == codeStr.upper():
                    found = w
                    break
        if found:
            return found
        else:
            return "Nothing"
    except Exception as e :
        print(e)
        return None
def urlEncode(codeStr):
    try:
        result = ""
        q_spe = ""
        q = quote(codeStr)
        q_plus= quote_plus(codeStr)
        if q_plus.find(".") >= 0:
            q_spe = q_plus.replace(".","%2E")
        result = q + "\n" + q_plus
        if q_spe:
            result = q + " \n" + q_plus + "\n" +q_spe
        return result
    except Exception as e:
        print(e)
        return None
def urlDecode(codeStr):
    try:
        result = unquote(codeStr)
        return result
    except Exception as e:
        print(e)
        return None
def searchContent(contentStr):
    searchUi.openWindow(contentStr)
def sqlSpace2Comment(coderStr):
    contentDes = spaceToComment.description()
    contentVal = spaceToComment.sqlEncode(coderStr)
    result = contentDes + "\n 编码结果: " + contentVal
    return result
def sqlDbWrite(dStr:dict):
    contentDes = doublewrite.description()
    contentVal = doublewrite.sqlEncode(**dStr)
    result = contentDes + "\n 编码结果: " + contentVal
    return result
def b64UrlDecode(codeStr:str):
    padding_factor = (4 - len(codeStr) % 4) % 4
    codeStr += "="*padding_factor
    result = base64.b64decode(str(codeStr).translate(dict(zip(map(ord, u'-_'), u'+/'))))
    return str(result,encoding="utf-8")

def base64UrlDecode(codeStr:str):
    try:
        result = ""
        rlist = []
        if codeStr.find(" ") >=0:
            codeStr = codeStr.replace(" ","")
        if codeStr.find(".") >=0:
            blist = codeStr.split(".")
            for b in blist:
                rlist.append(b64UrlDecode(b))
            result = ".".join(rlist)
        else:
            result = b64UrlDecode(codeStr)
        return result
    except Exception as e:
        print(e)
        return "编码错误!"
def b64Encode(codeStr:str):
    try:       
        if isinstance(codeStr,bytes):
            result = base64.urlsafe_b64encode(codeStr).replace(b'=', b'')
        else:
            codeStr = codeStr.encode("utf-8")
            result = base64.urlsafe_b64encode(codeStr).replace(b'=', b'')
        return str(result,"utf-8")
    except Exception as e:
        print(e)
        return "编码错误!"    
def base64UrlEncode(codeStr:str):
    try:
        result = ""
        rList = []
        codeStr = codeStr.strip()
        if codeStr.find(".")>=0:
            blist = codeStr.split(".")
            for b in blist:
                rList.append(b64Encode(b))
            result = '.'.join(rList)
        else:
            result = b64Encode(codeStr)
        return result
    except Exception as e:
        print(e)
        return "编码错误!" 